package com.naton.common.ui;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewbinding.ViewBinding;


import com.naton.common.viewmodel.BaseViewModel;

import java.util.Objects;

/**
 * 整合ViewModel
 * @param <VB>
 */
public abstract class BaseVMFragment<VB extends ViewBinding> extends BaseVBFragment<VB> {

    protected BaseViewModel mViewModel;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViewModel();
        initView();
    }

    /**
     * 初始化ViewModel
     */
    protected abstract void initViewModel();

    private void initView() {
        if (mViewModel == null)
            return;
        //显示吐司
        mViewModel.getMToastMsg().observeForever(this::showToast);
        //显示和取消进度条
        mViewModel.getMShowProgress().observe(this , show ->{
            if (show){
                showProgress();
            }else {
                hideProgress();
            }
        });
    }

    protected <T extends BaseViewModel> T getActivityScopeViewModel(@NonNull Class<T> modelClass) {
        T t = new ViewModelProvider.NewInstanceFactory().create(modelClass);
        mViewModel = t;
        getLifecycle().addObserver(mViewModel);
        return t;
    }

    protected <T extends ViewModel> T getApplicationScopeViewModel(@NonNull Class<T> modelClass) {
        return ViewModelProvider.AndroidViewModelFactory.getInstance(Objects.requireNonNull(getActivity()).getApplication()).create(
                modelClass);
    }
}
